const axios = require('axios');
const vscode = require('vscode');
const https = require('https');
const http = require('http');

const request = {
  initGiteeCli(url) {
    const gitee = axios.create({
      baseURL: `${url}/`,
      timeout: vscode.workspace.getConfiguration('HiSmartLiteReview').get('maxTimeoutInternal') * 1000,
      headers: {
        'content-type': 'application/json;charset=UTF-8',
      },
      httpsAgent: new https.Agent(
        {
          rejectUnauthorized: false,
        }
      ),
    });
    gitee.interceptors.request.use(async (config) => {
      return config;
    }, (error) => {
      return Promise.reject(error);
    });
    gitee.interceptors.response.use(this.giteeResolvedCallback, this.giteeRejectCallback);
    return gitee;
  },

  giteeRejectCallback(error) {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          return Promise.reject(error.response.data.message || '');
        default:
          return Promise.reject(error.response.data.message || error.response.data.error || '');
      }
    } else {
      if (error.message.includes('timeout')) {
        vscode.window.showErrorMessage('gitee interface timeout');
      }
      return Promise.reject(error?.message);
    }
  },

  giteeResolvedCallback(response) {
    if (!response.data) {
      return Promise.resolve('success');
    }
    let data = { data: response.data };
    if (response.headers && response.headers['x-total'] && response.headers['x-total-pages']) {
      data['dataSize'] = {
        total: Number(response.headers['x-total']),
        totalPages: Number(response.headers['x-total-pages'])
      };
    }
    if (response.headers && response.headers.total_count && response.headers.total_page) {
      data['dataSize'] = {
        total: Number(response.headers.total_count),
        totalPages: Number(response.headers.total_page)
      };
    }
    return Promise.resolve(data);
  }
};
module.exports = request;